package deanandjames.sound;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class SoundLoader {
	private final Map<String, SoundInfo> soundMap;

	public SoundLoader(String soundsFilename) {
		soundMap = new HashMap<String, SoundInfo>();
		loadSoundsFile("resources/sounds/" + soundsFilename);
	}

	public void play(String name) {
		final SoundInfo audioClipInfo = soundMap.get(name);
		if (audioClipInfo == null) {
			System.out.println("Error: " + name + "not stored");
		} else {
			audioClipInfo.play(false);
		}
	}

	private void load(String name, String fileName) {
		if (soundMap.containsKey(name)) {
			System.out.println("Error: " + name + "already stored");
		} else {
			soundMap.put(name, new SoundInfo(name, fileName));
			System.out.println("-- " + name + "/" + fileName);
		}
	}

	private void loadSoundsFile(String soundsFile) {
		System.out.println("Reading file: " + soundsFile);
		try {
			final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(soundsFile)));
			String line;
			while ((line = reader.readLine()) != null) {
				if (line.length() == 0) {
					continue;
				}
				if (line.startsWith("//")) {
					continue;
				}
				StringTokenizer tokens = new StringTokenizer(line);
				if (tokens.countTokens() != 2) {
					System.out.println("Wrong number of arguments for " + line);
				} else {
					String name = tokens.nextToken();
					String fileName = tokens.nextToken();
					load(name, fileName);
				}
			}
			reader.close();
		} catch (final IOException e) {
			System.out.println("Error reading file: " + soundsFile);
			System.exit(1);
		}
	}
}
